package com.zz.cogo.upload.service;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;

@Component
public class FileDfsService {

	@Autowired
	private FastFileStorageClient storageClient;
	/**
	 *     支持上传的文件类型
	 */
	private static final List<String> suffixes = Arrays.asList("image/png","image/jpeg","image/jpg");

	/**
	 * 上传文件
	 */
	public String upload(MultipartFile file) throws Exception {

		String type = file.getContentType();
		if (!suffixes.contains(type)) {
			System.out.println("上传文件失败，文件类型不匹配："+type);
			return null;
		}

//		BufferedImage image = ImageIO.read(file.getInputStream());
//		if (image == null) {
//			System.out.println("上传失败，文件内容不符合要求");
//			return null;
//		}

		StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
		// 获得文件上传后访问地址
		String fullPath = storePath.getFullPath();
		// 打印访问地址
		System.out.println("fullPath = " + fullPath);
		return storePath.getFullPath();
	}

	/**
	 * 删除文件
	 */
	public void deleteFile(String fileUrl) {
		if (StringUtils.isEmpty(fileUrl)) {
			System.out.println("fileUrl == >>文件路径为空...");
			return;
		}
		try {
			StorePath storePath = StorePath.parseFromUrl(fileUrl);
			storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
